import { debounce } from 'lodash';
import { RefObject, useLayoutEffect, useRef, useState } from 'react';

export const DEFAULT_DEBOUNCE_INTERVAL = 200;

function useClientRect<T extends HTMLElement>(
  debounceInterval: number = DEFAULT_DEBOUNCE_INTERVAL,
  realtime: boolean = false
): [DOMRect, RefObject<T>] {
  const ref = useRef<T>(null);
  const [rect, setRect] = useState<DOMRect>(new DOMRect());

  useLayoutEffect(() => {
    if (!ref.current) return;

    const resize = debounce(() => {
      if (ref.current) {
        const domRect = ref.current.getBoundingClientRect();
        if (domRect.width !== 0) {
          setRect(ref.current.getBoundingClientRect());
        }
      }
    }, debounceInterval);
    resize();

    if (typeof ResizeObserver === 'function') {
      let resizeObserver = new ResizeObserver(resize) as any;
      resizeObserver.observe(ref.current);
      return () => {
        resizeObserver.disconnect();
        resizeObserver = null;
      };
    } else {
      window.addEventListener('resize', resize);
      return () => {
        window.removeEventListener('resize', resize);
      };
    }
  }, [debounceInterval]);

  return [rect, ref];
}

export default useClientRect;

// demo
// const [rect, ref] = useClientRect<HTMLDivElement>(500);
// <div ref={ref}></div>
